package com.example.citydev;

import java.io.ByteArrayOutputStream;
import org.apache.commons.codec.binary.Base64;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
//ws

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class NuovaSegnalazione extends Activity implements OnClickListener {
	Button btn;
	int CAMERA_PIC_REQUEST = 0;
	ImageView imgView;
	protected LocationManager locationManager;

	private static final String NAMESPACE = "http://WSpkg/";
	private static String MYIP = "10.0.0.11";
	private static String URL = "http://" + MYIP
			+ ":8080/CityDevApp-war/CityDevWS?WSDL";
	private static final String METHOD_NAME = "AddProgetto";
	private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
	private static String risultatoWS = "";
	private static String segnalatore = "";
	private static String imgBase64 = "";
	TextView tvWS;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nuova_segnalazione);
		tvWS = (TextView) findViewById(R.id.ws);
		Bundle bundle = this.getIntent().getExtras();
		segnalatore = bundle.getString("user");

		imgView = (ImageView) findViewById(R.id.img_preview);

		btn = (Button) findViewById(R.id.buttonCapturePhoto);
		btn.setOnClickListener(this);
		btn = (Button) findViewById(R.id.send);
		btn.setOnClickListener(this);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000, 10, new MyLocationListener());
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buttonCapturePhoto:
			Intent camera_intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
			break;
		case R.id.send:
			tvWS.setText("");
			AsyncCallWS task = new AsyncCallWS();
			//ImageView img = (ImageView) findViewById(R.id.img_preview);
			//imgBase64 = getBase64(img);
			//Log.e("BMP",imgBase64);
			task.execute();
			break;
		}

	}

	private String getBase64(ImageView img) {
		 
		Bitmap selectedImage = ((android.graphics.drawable.BitmapDrawable) img
				.getDrawable()).getBitmap();
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		byte[] byteArray = stream.toByteArray();

		return Base64.encodeBase64(byteArray).toString();   
	}

	public static String invokeWSMethod(String descrizione, String gps_position) {
		String resTxt = null;
		// Create request
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		// Property which holds input parameters
		PropertyInfo par1 = new PropertyInfo();
		// Set Name
		par1.setName("descrizione");
		// Set Value
		par1.setValue(descrizione);
		// Set dataType
		par1.setType(String.class);
		// Add the property to request object
		request.addProperty(par1);
		PropertyInfo par2 = new PropertyInfo();
		// Set Name
		par2.setName("photourl");
		// Set Value
		par2.setValue("");
		// Set dataType
		par2.setType(String.class);
		// Add the property to request object
		request.addProperty(par2);
		PropertyInfo par3 = new PropertyInfo();
		// Set Name
		par3.setName("gps_position");
		// Set Value
		par3.setValue( gps_position );
		// PER DEBUG:
		//par3.setValue("45.071823,7.736725");
		// Set dataType
		par3.setType(String.class);
		// Add the property to request object
		request.addProperty(par3);
		PropertyInfo par4 = new PropertyInfo();
		// Set Name

		par4.setName("segnalatore");
		// Set Value
		par4.setValue(segnalatore);
		// Set dataType
		par4.setType(String.class);
		// Add the property to request object
		request.addProperty(par4);
		PropertyInfo par5 = new PropertyInfo();
		// Set Name
		par5.setName("responsabile");
		// Set Value
		par5.setValue("responsabile");
		// Set dataType
		par5.setType(String.class);
		// Add the property to request object
		request.addProperty(par5);

		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		// Set output SOAP object
		envelope.setOutputSoapObject(request);
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			// Invoke web service
			androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
			// Get the response
			SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
			// Assign it to resTxt variable static variable
            Log.e("anale",response.toString());
			resTxt = response.toString();
			risultatoWS = response.toString();
		} catch (Exception e) {
			// Print error
			e.printStackTrace();
			// Assign error message to resTxt
			resTxt = "Error occured";
		}
		// Return resTxt to calling object
		return resTxt;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0:
			if (resultCode == RESULT_OK) {
				Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
				imgView.setImageBitmap(thumbnail);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.nuova_segnalazione, menu);
		return true;
	}

	private class MyLocationListener implements LocationListener {
		TextView gpsdata = (TextView) findViewById(R.id.datigps);

		public void onLocationChanged(Location location) {
			String message = "" + location.getLongitude() + " "
					+ location.getLatitude();
			gpsdata.setText(message);
		}

		public void onStatusChanged(String s, int i, Bundle b) {
			String message = "Nessuna copertura GPS";
			gpsdata.setText(message);
		}

		public void onProviderDisabled(String s) {
			String message = "Gps Spento";
			gpsdata.setText(message);
		}

		public void onProviderEnabled(String s) {
			String message = "Gps in accensione";
			gpsdata.setText(message);
		}

		// web service

	}

	private class AsyncCallWS extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			String descrizione = ((TextView) findViewById(R.id.descrizione))
					.getText().toString();
			String gps_position = ((TextView) findViewById(R.id.datigps))
					.getText().toString();

			NuovaSegnalazione.invokeWSMethod(descrizione, gps_position);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Set response
			if (risultatoWS.equals("0"))
				tvWS.setText("Segnalazione eseguita");
			else if(risultatoWS.equals("1"))
				    tvWS.setText("Campo vuoto");
            else
                tvWS.setText("Errore" +risultatoWS);
		}

		@Override
		protected void onPreExecute() {
			tvWS.setText("Invio segnalazione in corso..");
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}

	}
}